/*
 *
 *  Copyright (C) 2009 GSyC/LibreSoft
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *
 */

package com.LibreGeoSocial.App;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.LibreGeoSocial.Api.GeoNode;
import com.LibreGeoSocial.Api.GeoNodePositionComparator;
import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.Api.Note;
import com.LibreGeoSocial.App.Routes.LocationService;
import com.LibreGeoSocial.App.Utils.LocationUtils;

public class NoteList extends GenericList {

	static private ArrayList<GeoNode> mNodeList;
	
	NoteAdapter mAdapter; 
	
	// Menu
	private static final int MENU_ADD_NOTE = Menu.FIRST + 1;
	private static final int MENU_LIST_NOTES = Menu.FIRST + 2;
		
	// Context menu
	private static final int MENU_DELETE_NOTE = Menu.FIRST + 1;
	private static final int MENU_PRIVACY_NOTE = Menu.FIRST + 2;
	
	private static final int REQUEST_PREFERENCES = 1;
	
	
	private static final int DIALOG_ADD_NOTE = 0;
	
	private EditText title;
	private EditText body;
	
	private static Boolean near_notes;
	
	public static Note note;
	
	private static NoteList pointerObject = null;
	
	private Thread th = null;
	
	private static Integer pageNote = 1;
	
	
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);    
        
        getData();
        
        pointerObject = this;
        near_notes = true;

	}
	
	private void getData()
	{
		LibreGeoSocial.getInstance().setPageNote(pageNote);
		
		th = new Thread(){
        	public void run(){ 
        		
        		// Get the data
        		mNodeList = LibreGeoSocial.getInstance().getNotes(0.0,null);
        		GeoNodePositionComparator comparator = new GeoNodePositionComparator();
        		Collections.sort(mNodeList, comparator);
        		        				        		
        		
        		// init the adapter
        		handler_Adapter.sendEmptyMessage(0);
			}
		};
		

		showProgressDialog("Notes", "Downloading notes", th);
		
	}
	
	/** This adapter 
	 */
	private Handler handler_Adapter = new Handler() {
		@Override
		public void handleMessage(Message msg) {			
			
			initAdapter();
		}
	};
	
	private void initAdapter() 
	{
		if (mAdapter == null )
		{
		
	        mAdapter = new NoteAdapter (this); 
	        setListAdapter(mAdapter);
	        
	        
	        // Init gestures
	        GesturesHandler gestureHand = new GesturesHandler();        
	        gestureHand.initGestures(this, R.raw.gestures);
	        
	        Hashtable<Object, Object> htGestures = new Hashtable<Object, Object>();
	        
	
			try {
		        
				/* Set the static methods that execute when gesture is recognize */
		        Class c = NoteList.class;
		        Method m = c.getDeclaredMethod("GestureNext", (Class[]) null);
				Method m2 = c.getDeclaredMethod("GesturePrevious", (Class[]) null);
				
				htGestures.put((Object)"Previous", m );
				htGestures.put((Object)"Next", m2 );
				
			} catch (NoSuchMethodException e) {			
				e.printStackTrace();
			}        
	
			gestureHand.setGestures(htGestures);
		
		}
		
		// Update the adapter
		mAdapter.notifyDataSetChanged();
		
		// Send message to close the progressDialog
		handler_PDialog.sendEmptyMessage(0);		
		
		// Stop the thread
		th.stop();
	}
	
	public static void GestureNext ()
	{		
		if (pointerObject == null)
			return;
				
		pageNote++;
		pointerObject.getData();
		return ;
		
	}
	
	
	
	public static void GesturePrevious ()
	{	
		if (pointerObject == null)
			return;
		
		pageNote--;
		pointerObject.getData();
		return;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View view,  ContextMenuInfo menuInfo)
	{ 
		
		super.onCreateContextMenu(menu, view, menuInfo);

		menu.add (0, MENU_DELETE_NOTE, 0, "Delete Note");
		menu.add (0, MENU_PRIVACY_NOTE, 0, "Change Privacy");         
		
	}
	
	
	@Override
	public boolean onContextItemSelected(MenuItem item) 
	{
		
		
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		note = (Note) mNodeList.get(info.position);
		
		switch (item.getItemId()) {
		
			case MENU_DELETE_NOTE:
				
				LibreGeoSocial.getInstance().deleteNote(note.getId());
				mNodeList.remove(info.position);
				setListAdapter(mAdapter);
				
				Toast.makeText(getBaseContext(), 
  					   "Note deleted correctly!", Toast.LENGTH_LONG).show();
				
				
				break;
				
			case MENU_PRIVACY_NOTE:
				
				Intent i = new Intent(this,LGS_Preferences.class);				
				startActivityForResult(i,REQUEST_PREFERENCES);
				
				break;
		
		}
		
		return true;
	}
	
	protected void onActivityResult (int requestCode, int resultCode, Intent data) {	 
		
		switch (requestCode) { 
		
	    	case REQUEST_PREFERENCES:
	    		
	    		// User text   
        	    SharedPreferences sharedPreferences = 
        	    	PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        		// Update state in twitter
        		String notePrivacy = 
        			sharedPreferences.getString (LGS_Preferences.KEY_APP_NOTE_PRIVACY, "friends");
        		
				if ( LibreGeoSocial.getInstance().setPrivacyNode(note.getId(), LibreGeoSocial.getInstance().PRIVACY_FRIENDS, true ))
					
	        		Toast.makeText(getBaseContext(), 
	  					   "Upload note privacy correctly!!", 
	  					   Toast.LENGTH_LONG).show();
				
				else
					
					Toast.makeText(getBaseContext(), 
		  					   "There is a problem with the privacy!", 
		  					   Toast.LENGTH_LONG).show();
	    		
	    		break;
	    		
		}
		
	}	
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_ADD_NOTE, 0, "Add note")
        		.setIcon(R.drawable.comment_add_48)
                .setAlphabeticShortcut('A');
        
        menu.add(0, MENU_LIST_NOTES, 0, "Near notes")
			.setIcon(R.drawable.comment_38)
	        .setAlphabeticShortcut('B');
		        
        return true;
    }
	
    @Override
    public boolean onOptionsItemSelected (MenuItem item) {
    	
    	switch (item.getItemId()) {
    	
    		case MENU_ADD_NOTE:
    			
    			showDialog(DIALOG_ADD_NOTE);
    			
    			break;
    			
    		case MENU_LIST_NOTES:
    			
    			if (near_notes)
    			{
    				mNodeList = LibreGeoSocial.getInstance().getNotes(2.0,null);
    				near_notes = false;
    				item.setTitle("All notes");
    				item.setIcon(R.drawable.mundo);
    			}
    			else
    			{
    				mNodeList = LibreGeoSocial.getInstance().getNotes(0.0,null);
    				near_notes = true;
    				item.setTitle("Near notes");
    				item.setIcon(R.drawable.comment_38);
    			}
    			
    			
    			GeoNodePositionComparator comparator = new GeoNodePositionComparator();
    			Collections.sort(mNodeList, comparator);
    			mAdapter.notifyDataSetChanged();
    			
    			
    			
    			break;
    	}
    	
    	return super.onOptionsItemSelected(item);
    }
    
	
	@Override
	protected void onResume(){
        super.onResume();

    }
    @Override
    protected void onPause(){
       super.onPause();

    }
	
    protected void onListItemClick(ListView l, View v, int position, long id) {
        
    	Note note = (Note) mNodeList.get(position);
		
    	Intent i = new Intent(this, NoteCard.class);
    	
    	i.putExtra("title", note.getTitle() );
    	i.putExtra("body", note.getBody() );
    	i.putExtra("date", note.getSince() );
    	i.putExtra("latitude", note.getLatitude() );
    	i.putExtra("longitude", note.getLongitude() );
    	i.putExtra("distance", getDistance(note.getLatitude(), note.getLongitude(), note.getLocation()).toString());
    	
    	startActivity(i);
        	

    }
    
    @Override
    protected Dialog onCreateDialog(int id) {       
    	
    	switch (id) {
    	
	    	case DIALOG_ADD_NOTE:
	    		
	    		LayoutInflater factory = LayoutInflater.from(this);
	    		final View textEntryView = factory.inflate(R.layout.note, null);
	    		
	    		title = (EditText) textEntryView.findViewById (R.id.txtTitle);
	    		body = (EditText) textEntryView.findViewById (R.id.txtBody);
	    		
		        return new AlertDialog.Builder(this)	        
		        .setTitle("Add note")
		        .setView(textEntryView)
		        .setPositiveButton("add", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            	
		                /* User clicked OK so do some stuff */ 
		            	
		            	Note note = new Note (null, 
		            						  title.getText().toString(), 
		            						  body.getText().toString(),
		            						  LocationService.getCurrentLocation().getLatitude(),
		            						  LocationService.getCurrentLocation().getLongitude(),
		            						  LocationService.getCurrentLocation().getAltitude(),
		            						  null, null);
		            	
		            	
		            	if ( LibreGeoSocial.getInstance().createNote(note) )
		            	{
		            		Toast.makeText(getBaseContext(), 
			     					   "Note added correctly!",
			     					   Toast.LENGTH_LONG).show();
		            		
		            		if (near_notes)
		            			mNodeList = LibreGeoSocial.getInstance().getNotes(2.0,null);
		            		else
		            			mNodeList = LibreGeoSocial.getInstance().getNotes(0.0,null);
		            		
		            		mAdapter.notifyDataSetChanged();
		            		
		            	}
		            	else
		            	{
		            		Toast.makeText(getBaseContext(), 
			     					   "Error while the status was setted: " + 
			     					   LibreGeoSocial.getInstance().getLastMsgServer(), 
			     					   Toast.LENGTH_LONG).show();
		            	}
		            }
		        })
		        .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		
		                /* User clicked cancel so do some stuff */
		            }
		        })
		        .create();

        	
    	}
		return null;
    
	}
    
    private static String getDistance(Double longitude, Double latitude, Location location){
    	String distString = null;
        
		if ( latitude==-1.0 && 
			 longitude==-1.0)
		{
			distString = "Unknow Location";
		}
		else
		{
			
			// Calculate distance
			float dist = LocationUtils.calculateDistance (LocationService.getCurrentLocation(), 
														  location);
			
			distString = LocationUtils.displayDistance(dist, LocationUtils.AUTO);
		}
		return distString;
    }

	public static class NoteAdapter extends BaseAdapter {

		private Context mContext;
		
		public NoteAdapter (Context c) {
            mContext = c;
        }

		public int getCount() {
			// TODO Auto-generated method stub
			return mNodeList.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view;
			
	        if (convertView == null) {
	            // Make up a new view
	            LayoutInflater inflater = (LayoutInflater) mContext
	                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.generic_list, null);
	        } else {
	            // Use convertView if it is available
	            view = convertView;
	        }
			
	        
	        Note note = (Note) mNodeList.get(position);	       	       

	        ImageView img = (ImageView) view.findViewById(R.id.image);
	        img.setImageResource(R.drawable.paper_pencil_48);
			
			TextView t = (TextView) view.findViewById(R.id.title);
			t.setText(note.getTitle());
			
			String distString = "";
			
	        distString = getDistance(note.getLatitude(), note.getLongitude(),note.getLocation());
			
			/*
			// Calculate distance
			if ( note.getLatitude()==-1.0 && 
				 note.getLongitude()==-1.0)
			{
				distString = "Unknow Location";
			}
			else
			{
				float dist = LocationUtils.calculateDistance (LocationService.getCurrentLocation(), 
															  note.getLocation());
				
				distString = LocationUtils.displayDistance(dist, LocationUtils.AUTO);
			}
			*/
			t = (TextView) view.findViewById(R.id.owner);
			t.setText("Dist: " + distString + "\n" + note.getBody());
	        
			return view;
	        
		}

	}
}


